import java.util.List;
import java.util.LinkedList;

public class ConnectionPool{
    private List<Connection> connections = new LinkedList<Connection>();
    private int counter;

    private synchronized int tickCounter(){
        counter++;
        return counter;
    }

    public Connection getConnection(){
        //寻找空闲的连接
        synchronized(this){
            for(Connection conn : connections){
                if(conn.isIdle()){
                    conn.startWork();
                    return conn;
                }
            }
        }

        //获取连接号
        int connectionNumber = this.tickCounter();

        //找不到空闲的连接，创建一个新的连接
        Connection newConnection = new ConnectionImpl(connectionNumber);
        newConnection.startWork();

        //将新的连接加入到连接池中
        synchronized(this){
            connections.add(newConnection);
        }

        //返回新的连接
        return newConnection;
    }
}
